<template>
    <div class="registration-list">
        <nav-header>
            <template slot="menuBefore">
                <li>
                    <router-link to="/life/events/events-management" tag="a"
                        >赛事管理&gt;</router-link
                    >
                </li>
                <li>
                    <a href="javascript:;" @click="linkTo(eventsId)"
                        >{{ infoDetail.name }}&gt;</a
                    >
                </li>
                <li class="gap">报名名单</li>
            </template>
        </nav-header>
        <section class="registration-container">
            <h3>{{ infoDetail.name }}</h3>
            <div class="output-row">
                <el-button type="primary" @click="getAllData"
                    >导出名单</el-button
                >
            </div>
            <div class="project-info">
                <template>
                    <el-tabs v-model="tabActive" type="card">
                        <el-tab-pane
                            v-for="(item1, inx) of infoDetail.project"
                            :key="inx"
                            :label="item1.name"
                            :name="item1.id"
                        >
                            <div
                                class="zh-table-contents"
                                v-loading="loading.status"
                                :element-loading-text="loading.txt"
                            >
                                <el-table :data="registrationData" border>
                                    <el-table-column
                                        prop="user_name"
                                        label="用户"
                                        align="center"
                                        show-overflow-tooltip
                                    ></el-table-column>
                                    <el-table-column
                                        prop="user_number"
                                        label="账号"
                                        align="center"
                                        show-overflow-tooltip
                                    ></el-table-column>
                                    <el-table-column
                                        label="学段年级班级"
                                        align="center"
                                        show-overflow-tooltip
                                    >
                                        <template slot-scope="scope">{{
                                            scope.row.org_name == ""
                                                ? "未绑定"
                                                : scope.row.org_name
                                        }}</template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="role_name"
                                        label="角色"
                                        align="center"
                                        show-overflow-tooltip
                                    ></el-table-column>
                                    <!-- 自定义报名部分 -->
                                    <el-table-column
                                        v-for="(col, inx) in customCols"
                                        :key="inx"
                                        :prop="col.prop"
                                        :label="col.label"
                                        align="center"
                                        show-overflow-tooltip
                                    >
                                    </el-table-column>

                                    <el-table-column
                                        prop="status_txt"
                                        label="状态"
                                        align="center"
                                        show-overflow-tooltip
                                    ></el-table-column>
                                    <el-table-column
                                        label="操作"
                                        align="center"
                                    >
                                        <template slot-scope="scope">
                                            <el-button
                                                @click="goDetail(scope.row)"
                                                type="text"
                                                >详情</el-button
                                            >
                                            <el-button
                                                v-if="scope.row.status == 0"
                                                @click="passRow(scope.row)"
                                                type="text"
                                                >通过</el-button
                                            >
                                            <el-button
                                                v-if="scope.row.status == 0"
                                                @click="rejectRow(scope.row)"
                                                type="text"
                                                class="delete-button"
                                                >拒绝</el-button
                                            >
                                            <el-button
                                                v-if="scope.row.status == 2"
                                                @click="checkReason(scope.row)"
                                                type="text"
                                                >理由</el-button
                                            >
                                            <el-button
                                                v-if="scope.row.status == 2"
                                                @click="delRow(scope.row.id)"
                                                type="text"
                                                >删除</el-button
                                            >
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                    <div class="table-pagination" v-show="total_number > 10">
                        <el-pagination
                            @current-change="changeCurrentPage"
                            :current-page="page_index"
                            :page-sizes="[10, 20, 30, 40, 50, 100]"
                            :page-size="page_size"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total_number"
                        ></el-pagination>
                    </div>
                </template>
            </div>
        </section>
        <el-dialog
            class="registry-dialog"
            title="报名信息"
            :visible.sync="registryVisible"
            width="550px"
        >
            <el-form
                ref="registryInfo"
                :model="registryInfo"
                label-width="120px"
                label-position="left"
            >
                <el-form-item label="用户名:">{{
                    registryInfo.user_name
                }}</el-form-item>
                <el-form-item label="账号:">{{
                    registryInfo.user_number
                }}</el-form-item>
                <el-form-item
                    label="学段年级班级:"
                    v-if="registryInfo.org_name"
                    >{{ registryInfo.org_name }}</el-form-item
                >
                <el-form-item label="角色:">{{
                    registryInfo.role_name
                }}</el-form-item>
                <el-form-item label="联系方式:">{{
                    registryInfo.telphone
                }}</el-form-item>
            </el-form>
            <div class="form-footer-btns">
                <el-button type="primary" @click="registryVisible = false"
                    >确定</el-button
                >
            </div>
        </el-dialog>
        <el-dialog
            class="registry-dialog"
            title="拒绝"
            :visible.sync="rejectVisible"
            width="550px"
        >
            <el-form ref="rejectInfo">
                <el-form-item label>
                    <el-input
                        type="textarea"
                        placeholder="请输入拒绝理由"
                        v-model="rejectReason"
                        maxlength="140"
                        resize="none"
                        :autosize="{ minRows: 8 }"
                        show-word-limit
                    ></el-input>
                </el-form-item>
            </el-form>
            <div class="form-footer-btns">
                <el-button type="primary" @click="approve(2)">确定</el-button>
                <el-button @click="rejectVisible = false">取消</el-button>
            </div>
        </el-dialog>
        <el-dialog
            class="registry-dialog"
            title="拒绝理由"
            :visible.sync="checkVisible"
            width="550px"
        >
            <el-form ref="rejectInfo">
                <el-form-item label>{{ rejectInfo }}</el-form-item>
            </el-form>
            <div class="form-footer-btns">
                <el-button type="primary" @click="checkVisible = false"
                    >确定</el-button
                >
            </div>
        </el-dialog>
    </div>
</template>
<script>
import XLSX from "xlsx";
import FileSaver from "file-saver";
export default {
    data() {
        return {
            eventsId: this.$route.params.id,
            infoDetail: [], //赛事信息
            selected: [], // 选中的数据
            loading: {
                status: false,
                txt: "获取数据..."
            },

            registrationData: [], //名单数据
            customCols: [], //自定义部分标题数据
            tabActive: "1",
            projectId: "", //项目id
            // 分页：
            page_index: 1,
            page_size: 10,
            total_number: 0,
            registryVisible: false, //报名信息弹窗
            registryInfo: {}, //报名信息
            rejectId: "",
            rejectVisible: false, //拒绝弹窗
            rejectReason: "", //拒绝理由
            checkVisible: false, //拒绝理由弹窗
            rejectInfo: "" //查看拒绝详情
        };
    },
    created() {
        this.getDetail();
    },
    mounted() {},
    watch: {
        // 切换项目时，请求对应的名单数据
        tabActive(newVal, oldVal) {
            if (newVal != oldVal) {
                this.projectId = newVal;
                this.getRegistration();
            }
        }
    },
    computed: {},
    methods: {
        /**
         * 跳去赛事详情页
         * @param {Number} id 赛事 id
         */
        linkTo(id) {
            this.$router.push("/life/events/events-details/" + id);
        },
        /**
         * 获取赛事详情
         */
        getDetail() {
            let success = res => {
                this.infoDetail = res.data;
                if (!is_empty(res.data)) {
                    // 默认展示第一个项目的数据
                    this.projectId = res.data.project[0].id;
                    this.getRegistration();
                }
            };
            const params = {
                id: this.$route.params.id
            };
            this.$ajax.get("api/competition/match", {
                params,
                func: { success: success }
            });
        },

        /**
         * 获取报名名单
         */
        getRegistration() {
            this.customCols=[];
            let success = res => {
                this.total_number = res.data.data_sum;
                if(res.data.data.length>0){
                    let _data = res.data.data;
                    let registration_information =
                        res.data.data[0].information;
                    // 获取自定义表头
                    registration_information.forEach((item, index) => {
                        let col = {};
                        col.prop = "registration" + index;
                        col.label = item.name;
                        this.customCols.push(col);
                    });
                    // table数组添加跟表头对应的键值对
                    for (let i = 0; i < _data.length; i++) {
                        for (let j = 0; j < _data[i].information.length; j++) {
                            _data[i]["registration" + j] =
                                _data[i].information[j].value;
                        }
                    }
                    this.registrationData = _data;
                }
            };
            const params = {
                page_index: this.page_index,
                page_size: this.page_size,
                competition_id: this.$route.params.id,
                project_id: this.projectId
            };
            this.$ajax.get("api/competition/match_user", {
                params,
                func: { success: success }
            });
        },
        /**
         * 分页
         */
        changeCurrentPage(val) {
            this.page_index = val;
            this.getDetail();
        },
        //详情
        goDetail(val) {
            this.registryVisible = true;
            this.registryInfo = val;
        },
        //通过
        passRow(val) {
            this.rejectId = val.id;
            this.approve(1);
        },
        // 查看拒绝理由
        checkReason(val) {
            this.checkVisible = true;
            this.rejectInfo = val.reason;
        },
        // 拒绝
        rejectRow(val) {
            this.rejectReason = "";
            this.rejectId = val.id;
            this.rejectVisible = true;
        },

        /**
         * 赛事名单审批
         * @param {Number} status 1：通过；3：拒绝
         */
        approve(status) {
            const params = {
                id: this.rejectId,
                status: status,
                reason: status == 1 ? "" : this.rejectReason
            };
            let success = data => {
                this.$message.success(data.msg);
                this.getRegistration();
                this.rejectVisible = false;
            };
            this.$ajax.post("api/competition/match_user_approve", params, {
                func: { success: success }
            });
        },
        // 删除
        delRow(id) {
            this.$confirm("删除不可恢复，确定要删除吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                customClass: "confirm-them"
            })
                .then(() => {
                    this.sureDel(id);
                })
                .catch(() => {});
        },
        // 确定删除
        sureDel(id) {
            let success = res => {
                this.$message.success(res.msg);
                this.getRegistration();
            };
            let fail = res => {
                this.$message.error(res.msg);
            };
            this.$ajax({
                url: "api/competition/match_user",
                method: "delete",
                params: {
                    id: id
                },
                func: {
                    success: success,
                    fail: fail
                }
            });
        },
        /**
         * 获取全部数据后导出
         */
        async getAllData() {
            if (this.total_number <= this.page_size) {
                this.exportExcel(this.registrationData);
            } else {
                let All = [];
                let len = Math.ceil(this.total_number / 100);
                let success = res => {
                    All = [...All, ...res.data];
                };

                for (let i = 1; i <= len; i++) {
                    let params = {
                        competition_id: this.$route.params.id,
                        page_index: i,
                        page_size: 100
                    };

                    await this.$ajax.get("api/competition/match_user", {
                        params: params,
                        func: { success: success }
                    });
                }
                this.exportExcel(All);
            }
        },
        /**
         * 导出Excel表
         * @param {Array} allData 全部数据
         */
        exportExcel(allData) {
            if (allData.length === 0) {
                this.$message.info("还未有人报名~");
                return false;
            }

            let exportList = [];
            const defaultCellStyle = {
                font: { name: "Verdana", sz: 14, color: "FF00FF88" },
                fill: { fgColor: { rgb: "FFFFAA00" } }
            };
            const wopts = {
                bookType: "xlsx",
                bookSST: false,
                type: "binary",
                defaultCellStyle: defaultCellStyle,
                showGridLines: false
            };
            const wb = { SheetNames: ["Sheet1"], Sheets: {}, Props: {} };

            for (let i = 0; i <= allData.length - 1; i++) {
                let keyName = "";
                let val = "";
                let customObj = {}; //自定义部分
                for (let j = 0; j <= allData[i].information.length - 1; j++) {
                    customObj[allData[i].information[j].name] =
                        allData[i].information[j].value;
                }
                // 固定的部分数据
                const baseObj = {
                    用户: allData[i].user_name,
                    账号: allData[i].user_number,
                    学段年级班级:
                        allData[i].org_name == ""
                            ? "未绑定"
                            : allData[i].org_name,
                    角色: allData[i].role_name,
                    状态: allData[i].status_txt
                };
                exportList.push(Object.assign(baseObj, customObj));
            }
            wb.Sheets["Sheet1"] = XLSX.utils.json_to_sheet(exportList);
            wb.Sheets["Sheet1"]["!cols"] = [
                {
                    wpx: 110
                },
                {
                    wpx: 110
                },
                {
                    wpx: 120
                },
                {
                    wpx: 110
                },
                {
                    wpx: 80
                },
                {
                    wpx: 140
                },
                {
                    wpx: 140
                },
                {
                    wpx: 140
                },
                {
                    wpx: 140
                },
                {
                    wpx: 140
                },
                {
                    wpx: 140
                }
            ];

            //创建二进制对象写入转换好的字节流
            let tmpDown = new Blob([this.str2Buffer(XLSX.write(wb, wopts))], {
                type: "application/octet-stream"
            });
            FileSaver.saveAs(tmpDown, `报名名单-表格.xlsx`);
        },
        /**
         * 字符串转类型化数组
         * @param {String} str 字符串
         */
        str2Buffer(str) {
            if (typeof ArrayBuffer !== "undefined") {
                let buf = new ArrayBuffer(str.length);
                let view = new Uint8Array(buf);

                for (let i = 0; i != str.length; i += 1) {
                    view[i] = str.charCodeAt(i) & 0xff;
                }
                return buf;
            } else {
                let buf = new Array(str.length);

                for (let i = 0; i != str.length; i += 1) {
                    buf[i] = str.charCodeAt(i) & 0xff;
                }
                return buf;
            }
        }
    }
};
</script>
<style lang="scss">
.output-row {
    text-align: end;
    .el-button {
        padding: 0;
        width: 100px;
        height: 30px;
    }
}

.registration-container {
    .title-row {
        height: 32px;
        line-height: 32px;
        text-align: center;
        margin-bottom: 50px;
        padding: 0 180px;
        position: relative;
        h3 {
            text-align: center;
            font-size: 22px;
            font-weight: bold;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
        .btns-div {
            display: inline-block;
            position: absolute;
            right: 0;
            top: 0;
            .output-btn {
                padding: 0;
                width: 86px;
                height: 32px;
                margin-left: 20px;
            }
        }
    }
}
.registry-dialog {
    .form-footer-btns {
        text-align: center;
        padding-bottom: 40px;
        .el-button {
            padding: 0;
            width: 68px;
            height: 30px;
        }
    }
}
</style>